package com.zifeng.study.springbootredis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;

import javax.annotation.PostConstruct;

/**
 * @author 吴梓锋
 * @version 1.0.0
 * @date 2022/05/24 16:21:40
 * @description redis config
 */
@Configuration
public class RedisConfig {

    @Autowired
    private RedisTemplate redisTemplate = null;

    @PostConstruct
    public void init() {
        initRedisTemplate();
    }

    private void initRedisTemplate() {
        // 序列化器设置为string便于追踪
        RedisSerializer stringSerializer = redisTemplate.getStringSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
    }
    
    /**
     * 装载秒杀的lua脚本
     *
     * @return 脚本对象
     */
    @Bean("secKillScript")
    public DefaultRedisScript<String> secKillScript() {
        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(String.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/secKill.lua")));
        return redisScript;
    }

}

